package servicediscovery;

import org.apache.zookeeper.*;

import java.util.List;

public class ServiceDiscovery {
    private String zkAddress;
    private ZooKeeper zooKeeper;

    public ServiceDiscovery(String zkAddress) {
        this.zkAddress = zkAddress;
        connect();
    }

    private void connect() {
        try {
            this.zooKeeper = new ZooKeeper(zkAddress, 5000, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> discover(String serviceName) {
        try {
            // 获取服务节点列表
            String servicePath = "/services/" + serviceName;
            List<String> nodeNames = zooKeeper.getChildren(servicePath, true);

            // 获取每个服务节点的地址
            for (String nodeName : nodeNames) {
                byte[] data = zooKeeper.getData(servicePath + "/" + nodeName, false, null);
                System.out.println(serviceName + " node: " + nodeName + ", address: " + new String(data));
            }

            return nodeNames;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

